﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ECommon
{
    /// <summary>
    /// 类型工具
    /// </summary>
    public static class TypeTool
    {
        /// <summary>
        /// 判定类型是否可空
        /// </summary>
        /// <param name="type">要判断的类型</param>
        /// <returns>判定结果</returns>
        public static bool IsTypeNullable(Type type)
        {
            if (type.IsValueType)
            {
                Type typeTmp = Nullable.GetUnderlyingType(type);
                return typeTmp != null;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 获取真实变量名，对于可空类型，将获取其基础类型
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns>变量名</returns>
        public static string GetTypeName(Type type)
        {
            if (type.IsValueType)
            {
                Type typeTmp = GetUnderlineType(type);
                if (typeTmp == null)
                {
                    return type.Name;
                }
                else
                {
                    return typeTmp.Name;
                }
            }
            else
            {
                return type.Name;
            }
        }


        /// <summary>
        /// 获取一个类型的可空泛型类型的初始类，如果是不可空类型，直接返回本类
        /// </summary>
        /// <param name="type">原始类型</param>
        /// <returns>类型对象</returns>
        /// <exception cref="ArgumentNullException">传入参数为空</exception>
        private static Type GetUnderlineType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type", "类型参数为空");
            }
            Type typeTmp = Nullable.GetUnderlyingType(type);
            if (typeTmp == null)
            {
                return type;
            }
            else
            {
                return typeTmp;
            }
        }
    }
}
